#import "myWindowController.h"
#import "NSString+Additions.h"


@implementation myWindowController

//default outgoing port
#define DEFAULT_OSC_PORT 5001

- (void) awakeFromNib {
		
	//set up default prefs
	
//	[mDefaults setObject:[NSNumber numberWithFloat:[addListener floatValue]] forKey:kPlayRate];
//	[mDefaults setObject:[cDisplayWatchFolder stringValue] forKey:kWatchFolder];}

    [animate setStyle:NSProgressIndicatorSpinningStyle];
    [animate setIndeterminate:TRUE];
	currentName = @"nothing";
	[currentName retain];
	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:[fontSize intValue]]];
	
	if (![[NSUserDefaults standardUserDefaults] objectForKey:@"first_run"])
	{
		[self firstRun];
		[[NSUserDefaults standardUserDefaults] setObject:@"FALSE" forKey:@"first_run"];
	}

	
	
}

//handle drag and drop

//handle finder icon drag and drop

- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename {

	NSString * thePath;
	
	NSLog(@"here's the file that was dropped %@",filename);
	NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:[NSString stringWithContentsOfFile:filename]];
	
	
	//get file name and update variable
	currentName = filename;
	
	[mainWindow setTitle:currentName];
	
	
	[self clearWorkspace];			
	[[tabSource textStorage] appendAttributedString:attributedString];
	//		[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:14]];
	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:[fontSize intValue]]];
	
	

}


- (IBAction)simpleSave:(id)sender
{
	NSLog(currentName);
	
	if ([currentName isEqualToString:@"nothing"])
		[self saveCurrentfile:(id)sender];
	else {
		if([[[tabSource textStorage] string] writeToFile:currentName atomically:NO])
			NSLog(@"file saved");
	}
}

-(void)firstRun{
	
	NSString *thisBundlePath = [[NSBundle bundleForClass:[self class]] bundlePath];
	NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:[NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/Contents/Resources/xtab_intro.txt",thisBundlePath]]];
	
	//get file name and update variable
	currentName = [NSString stringWithFormat:@"%@/Contents/Resources/xtab_intro.txt", thisBundlePath];
	[mainWindow setTitle:[NSString stringWithFormat:@"xTab Intro"]];
	
	[self clearWorkspace];
	[[tabSource textStorage] appendAttributedString:attributedString];
	//	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:14]];
		[[tabSource textStorage] setFont:[NSFont fontWithName:@"Verdana" size:12]];
	[currentName retain];
	
	}

- (IBAction)openReadme:(id)sender{
	
	NSString *thisBundlePath = [[NSBundle bundleForClass:[self class]] bundlePath];
	[[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/README",thisBundlePath]];
}

- (IBAction)loadSample:(id)sender{

	
		NSString *thisBundlePath = [[NSBundle bundleForClass:[self class]] bundlePath];
	NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:[NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/sample.tab",thisBundlePath]]];
	
	//get file name and update variable
	currentName = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/sample.tab",thisBundlePath];
	[mainWindow setTitle:[NSString stringWithFormat:@"sample.tab",thisBundlePath]];
	
		[self clearWorkspace];
	[[tabSource textStorage] appendAttributedString:attributedString];
//	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:14]];
	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:[fontSize intValue]]];
	[currentName retain];
	}

- (IBAction)newFromTemplate:(id)sender{
	
	NSString *thisBundlePath = [[NSBundle bundleForClass:[self class]] bundlePath];
	NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:[NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/template.tab",thisBundlePath]]];
	
	//get file name and update variable
	currentName = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/template.tab",thisBundlePath];
	[mainWindow setTitle:[NSString stringWithFormat:@"template.tab",thisBundlePath]];
	
	[self clearWorkspace];
	[[tabSource textStorage] appendAttributedString:attributedString];
//	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:14]];
	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:[fontSize intValue]]];
	[currentName retain];
}

- (IBAction)changeFontSize:(id)sender{
	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:[fontSize intValue]]];
}

- (IBAction)newDoc:(id)sender
{
	[self clearWorkspace];
}


-(void)clearWorkspace{
	
	NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@""];
	[[tabSource textStorage] setAttributedString:attributedString];
//	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:14]];
	[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:[fontSize intValue]]];
	
}



- (IBAction)playMidi:(id)sender
{
	
	NSLog(@"starting conversion");
	
	[animate startAnimation:animate];
	//[self simpleSave:(id)sender];
	
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
	[nc addObserver:self selector:@selector(getMidiDataFromTerminal:) 
			   name:  NSFileHandleReadCompletionNotification object:nil];
	
	NSString *thisBundlePath = [[NSBundle bundleForClass:[self class]] bundlePath];
	NSString *tabPath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/tab", thisBundlePath];
	NSString *tempPath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/temp.tab", thisBundlePath];	
	NSString *sourcePath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/sample.tab", thisBundlePath];
	NSString *savePath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/temp.ps", thisBundlePath];
	NSString *fontsPath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab", thisBundlePath];
	NSString *midiPath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/%@.mid", thisBundlePath, [[[mainWindow title] lastPathComponent]stringByDeletingPathExtension]];

	
	//NSLog(@"path %@", tempPath);
	
	if([[[tabSource textStorage] string] writeToFile:tempPath atomically:NO])
	{
		NSLog(@"temp file saved");
		generateTAB = [[NSTask alloc] init];
		NSPipe* pipe = [NSPipe pipe];
		[pipe retain];
		
		[generateTAB setLaunchPath:tabPath];
		[generateTAB setArguments:[NSArray arrayWithObjects:tempPath, @"-fontpath", fontsPath, @"-midi", @"-o", midiPath, nil]];
		
		[generateTAB setStandardOutput:pipe];
		
		[generateTAB launch];
		
		
		//	[getPerlResults setStringValue:[[[NSString alloc] initWithData:[serverOutput readDataToEndOfFile] encoding:NSASCIIStringEncoding] autorelease]];	
		tabOutput = [pipe fileHandleForReading];	
		//	NSLog ([[NSString alloc] initWithData:[tabOutput readInBackgroundAndNotify] encoding:NSASCIIStringEncoding]); 
		[tabOutput readInBackgroundAndNotify] ;
		
		
	}
	
	else {
		//problems
		NSRunAlertPanel(@"Unable to write to temp file.", @":-(", nil, nil, nil);
		[animate stopAnimation:animate];
		return;
	}
	
}



- (IBAction)doIt:(id)sender
{

NSLog(@"starting conversion");

[animate startAnimation:animate];
	//[self simpleSave:(id)sender];

	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
	[nc addObserver:self selector:@selector(getDataFromTerminal:) 
			   name:  NSFileHandleReadCompletionNotification object:nil];
	
	NSString *thisBundlePath = [[NSBundle bundleForClass:[self class]] bundlePath];
	NSString *tabPath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/tab", thisBundlePath];
	NSString *tempPath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/temp.tab", thisBundlePath];	
	NSString *sourcePath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/sample.tab", thisBundlePath];
	NSString *savePath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/%@.ps", thisBundlePath, [[[mainWindow title] lastPathComponent]stringByDeletingPathExtension]];
	NSString *fontsPath = [NSString stringWithFormat:@"%@/Contents/Resources/lute_tab", thisBundlePath];

//NSLog(@"path %@", tempPath);

	//clear old temp file
	[[NSFileManager defaultManager] removeFileAtPath:tempPath handler:nil];
	
	//save new temp file
	
if([[[tabSource textStorage] string] writeToFile:tempPath atomically:NO])
	{
	NSLog(@"temp file saved");
	generateTAB = [[NSTask alloc] init];
	NSPipe* pipe = [NSPipe pipe];
	[pipe retain];

	[generateTAB setLaunchPath:tabPath];
	[generateTAB setArguments:[NSArray arrayWithObjects:tempPath, @"-fontpath", fontsPath, @"-C", @"-p", @"-o", savePath, nil]];
		
	[generateTAB setStandardOutput:pipe];

	[generateTAB launch];


//	[getPerlResults setStringValue:[[[NSString alloc] initWithData:[serverOutput readDataToEndOfFile] encoding:NSASCIIStringEncoding] autorelease]];	
	tabOutput = [pipe fileHandleForReading];	
//	NSLog ([[NSString alloc] initWithData:[tabOutput readInBackgroundAndNotify] encoding:NSASCIIStringEncoding]); 
	[tabOutput readInBackgroundAndNotify] ;
	
	
	}
	
	else {
	//problems
	NSRunAlertPanel(@"Unable to write to temp file.", @":-(", nil, nil, nil);
	[animate stopAnimation:animate];
	return;
	}
	
}


-(void)getDataFromTerminal:(NSNotification *)notification {
	
//	NSLog(@"got data");
	
	NSData * messageData = [[notification userInfo]
objectForKey:NSFileHandleNotificationDataItem];
	NSString *thisBundlePath = [[NSBundle bundleForClass:[self class]] bundlePath];
	
	id notificationObject=[notification object];
	if (notificationObject==tabOutput) {	
			   
		NSString * results= [[[NSString alloc] initWithData:messageData encoding:NSASCIIStringEncoding] autorelease];
		
	//NSLog (@"back from the terminal: %@",results);
	
	NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:results];	
	[[messages textStorage] appendAttributedString:attributedString];	
	[[messages textStorage] setFont:[NSFont fontWithName:@"Monaco" size:9]];
	
	if ([results containsString:@"may not be a valid"] || [results containsString:@"Bad"] )
		{
		NSRunCriticalAlertPanel(@"TAB Error:", results, nil, nil, nil);
		return;
			}
		
		
	
//	[messages insertText:results];
		
if(	[[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/%@.ps",thisBundlePath,[[[mainWindow title] lastPathComponent]stringByDeletingPathExtension]]])
NSLog(@"yay");
else
NSRunCriticalAlertPanel(@"TAB Error:", results, nil, nil, nil);
	
	//tab 4.3.19 copyright 1995-2003 by Wayne Cripps
		
		
		
				
		//put data in textview
		
		if (showMessageWindow){
		
	//	NSAttributedString *attributedString = [[NSAttributedString alloc]
// initWithString:results];
	
		//dont print the data
		
	///	[[getPerlResults textStorage] appendAttributedString:attributedString];
		
	//	[attributedString release];
	//	[getPerlResults scrollPoint:NSMakePoint(0.0, [getPerlResults frame].size.height)];
					
	//		NSLog (@"finished reading data");
		}
		
		
			//[tabOutput readInBackgroundAndNotify];
			
		[animate stopAnimation:animate];
		
			//NSLog(@"finishing up");
			
			[[NSNotificationCenter defaultCenter] removeObserver: self];
			
			return;
			
    }
	else { NSLog(@"no file handle");}
}

-(void)getMidiDataFromTerminal:(NSNotification *)notification {
	
	//	NSLog(@"got data");
	
	NSData * messageData = [[notification userInfo]
objectForKey:NSFileHandleNotificationDataItem];
	NSString *thisBundlePath = [[NSBundle bundleForClass:[self class]] bundlePath];
	
	id notificationObject=[notification object];
	if (notificationObject==tabOutput) {	
		
	NSString * results= [[[NSString alloc] initWithData:messageData encoding:NSASCIIStringEncoding] autorelease];
		
		//	[messages insertText:results];
		
		if(	[[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/Contents/Resources/lute_tab/%@.mid",thisBundlePath,[[[mainWindow title] lastPathComponent]stringByDeletingPathExtension]]])
			NSLog(@"yay got midi!");
		else {
			//if ([results containsString:@"may not be a valid"] || [results containsString:@"Bad"] )
			//{
				NSRunCriticalAlertPanel(@"Error Generating MIDI File:", results, nil, nil, nil);
			//	return;
			//}
		}
		
		//tab 4.3.19 copyright 1995-2003 by Wayne Cripps
		
		
		
		
		//put data in textview
		
		if (showMessageWindow){
			
			//	NSAttributedString *attributedString = [[NSAttributedString alloc]
			// initWithString:results];
			
			//dont print the data
			
			///	[[getPerlResults textStorage] appendAttributedString:attributedString];
			
			//	[attributedString release];
			//	[getPerlResults scrollPoint:NSMakePoint(0.0, [getPerlResults frame].size.height)];
			
			//		NSLog (@"finished reading data");
		}
		
		
		//[tabOutput readInBackgroundAndNotify];
		
		[animate stopAnimation:animate];
		
		//NSLog(@"finishing up");
		
		[[NSNotificationCenter defaultCenter] removeObserver: self];
		
		return;
		
    }
	else { NSLog(@"no file handle");}
}



- (IBAction)clearLog:(id)sender;
{
	[[messages textStorage] setAttributedString:[[NSAttributedString alloc] init]];	
	
}

- (IBAction)importFile:(id)sender;
{

	NSString * thePath;
	NSOpenPanel*	lPanel = [NSOpenPanel openPanel];
    [lPanel setAllowsMultipleSelection:NO];
	[lPanel setCanChooseDirectories:NO];
	
    if ([lPanel runModalForDirectory:nil file:nil types:nil]==NSOKButton) {
		thePath = [[lPanel filenames] objectAtIndex:0];
		
		
		NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:[NSString stringWithContentsOfFile:thePath]];
		
		//get file name and update variable
		currentName = thePath;
		[mainWindow setTitle:thePath];

	[self clearWorkspace];			
		[[tabSource textStorage] appendAttributedString:attributedString];
	//		[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:14]];
		[[tabSource textStorage] setFont:[NSFont fontWithName:@"Monaco" size:[fontSize intValue]]];
		
		//[[NSUserDefaults standardUserDefaults] setObject:thePath forKey:@"incomingDestination"];
		
	}		
		

};

- (IBAction)saveCurrentfile:(id)sender
{

	//NSLog(@"got here");
	//NSLog(@"current name is: %@",currentName);
	
		
		NSString * theSaveFileName;
		NSSavePanel*	lPanel = [NSSavePanel savePanel];

		[lPanel setTitle:@"xTAB save"];
		[lPanel setCanCreateDirectories:YES];
		
		if ([currentName isEqualToString:@"nothing"])
			currentName = @"MyGreatIntabulation.tab";
		
		
		
		if ([lPanel runModalForDirectory:nil file:[currentName lastPathComponent] types:nil]==NSOKButton) {
			theSaveFileName = [lPanel filename];
			currentName = [theSaveFileName copy];
				
//add .tab if it isnt there yet
			
			
			if (![[theSaveFileName pathExtension] isEqualToString:@"tab"])
	theSaveFileName = [theSaveFileName stringByAppendingPathExtension:@"tab"];
		//	NSLog(@"save file is: %@",theSaveFileName);

	NSString *thisBundlePath = [[NSBundle bundleForClass:[self class]] bundlePath];
	
	
if([[[tabSource textStorage] string] writeToFile:theSaveFileName atomically:NO])
{NSLog(@"file saved");
	[mainWindow setTitle:theSaveFileName];}


		}
};

- (void)dealloc{

	[generateTAB interrupt];
	[generateTAB terminate];
	generateTAB=nil;
	[super dealloc];
	[[NSNotificationCenter defaultCenter] removeObserver: self];
	[tabOutput closeFile];
	[tabOutput release];}


@end
